# -*- coding: utf-8 -*-
# @Time    : 2023/12/31  21:33
# @Author  : zhanghao
# @FileName: rule_actuator.py
# @Software: PyCharm
"""
    Description: 根据规则配置和内容重命名文件
"""
import collections
import os
import re

from config.config import Config
from config.logger import Logger
from domain.rule import Rule
from domain.rename import Rename
from core.ocr_result import OcrResult
from helper.file_helper import FileHelper


class RuleActuator:
    logger = Logger().get()

    config: Config
    rules: [Rule]

    def __init__(self, config: Config):
        self.logger.info('初始化规则数量: ' + str(len(config.rule_config.rules)))
        self.config = config
        self.rules = config.rule_config.rules
        for rule in self.rules:
            self.logger.info('规则执行器初始化：' + str(len(rule.rename)))
            for info in rule.rename:
                self.logger.info('ruleactuator:' + info.name + ' ' + info.info)

    # 遍历规则进行匹配
    def processContent(self, content: OcrResult):
        self.logger.info('识别文本，规则数量：' + str(len(self.rules)))

        new_file_name = ''
        for rule in self.rules:
            keyword = rule.keyword

            self.logger.info('processContent：' + keyword + ' len rename:' + str(rule.rename))
            # 确定一个规则类型
            if keyword in content.text:
                execute_result = self.ruleExecute(rule, content)
                new_file_name = self.composeName(execute_result, rule.separator)
                break

        self.logger.info('processContent：' + content.text + ' filename:' + new_file_name)
        return new_file_name

    # 对文件重命名
    def doRename(self, new_name, old_name, file_type):
        if not new_name or len(new_name) == 0:
            return

        # 获取文件路径
        file_path = FileHelper.fetchDirName(old_name)
        file_path = file_path + '/' + new_name + file_type
        os.rename(old_name, file_path)

    # 执行规则
    def ruleExecute(self, rule: Rule, content: OcrResult):
        self.logger.info('ruleExecute' + rule.keyword + ' rule len' + str(len(rule.rename)))
        execute_result = collections.OrderedDict()

        rule_size = 0
        for rename in rule.rename:
            self.logger.info('ruleExecute---' + rename.name + ' ' + rename.info)
            if rename.name != 'renameCaseType':
                rule_size += 1

            result = ''
            if rename.match_type == 'regex':
                result = self.regexExecute(rename, content)
            elif rename.match_type == 'keyword':
                result = self.keywordExecute(rename, content)

            self.logger.info(str(rule_size) + ':识别结果' + rename.name + ' ' + result)
            execute_result[rename.name] = result

        if len(execute_result) < rule_size:
            execute_result.clear()
        self.logger.info(execute_result)
        return execute_result

    # 正则执行器
    def regexExecute(self, rename: Rename, content: OcrResult):
        result = ''
        if rename.name == 'caseNo':
            pattern = re.compile(rename.info)
            search_result = re.search(pattern, content.text)
            if search_result:
                # 找到匹配的正则内容
                result = search_result.group()
        elif rename.name == 'defendantName':
            pattern = re.compile(rename.info)
            search_result = re.findall(pattern, content.text)
            if search_result and len(search_result) > 0:
                for defendant in search_result:
                    if len(result) == 0:
                        result = defendant[1]
                    else:
                        if defendant[1] not in result:
                            result = result + '、' + defendant[1]
        else:
            pattern = re.compile(rename.info)
            search_result = re.findall(pattern, content.text)
            if search_result and len(search_result) > 0:
                result = search_result[0]
        return result

    # 关键字执行器
    def keywordExecute(self, rename: Rename, content: OcrResult):
        keyword = rename.info

        execute_result = ''
        # 拆分关键字
        result = keyword.split('+')
        if result and len(result) == 2:
            suffix = result[1]
            delimiter = result[0]

            delimiters = delimiter.split('#')
            for deli in delimiters:
                if deli in content.text:
                    execute_result = deli + suffix
        else:
            suffix = keyword
            if suffix in content.text:
                execute_result = suffix
        return execute_result

    # 根据识别结果，重新组装文件名称
    def composeName(self, execute_result: collections.OrderedDict, separator):
        new_file_name = ''

        self.logger.info(execute_result)
        # 先判断是否存在renameCaseType类型
        case_type = ''
        if 'renameCaseType' in execute_result.keys():
            case_type = execute_result['renameCaseType']

        # 遍历
        name_list = []
        for key, result in execute_result.items():
            if key == 'renameCaseType':
                continue

            if key == 'caseType' and len(case_type) > 0:
                name_list.append(case_type)
            else:
                name_list.append(result)

        self.logger.info(name_list)
        new_file_name = separator.join(name_list)
        return new_file_name
